package server

import (
	"src/zeus/iserver"
	"src/zeus/logger"
	"src/zeus/msgdef"
	"time"
)

type serverMsgProc struct {
	srv *Server
}

func (p *serverMsgProc) getMsgHandlers(spaceID uint64) iserver.IMsgHandler {

	if spaceID == 0 {
		return p.srv.MsgHandler
	}
	e := p.srv.GetEntity(spaceID)
	if e == nil {
		return nil
	}

	if es, ok := e.(iserver.IEntities); ok {
		return es.GetMsgHandler()
	}

	return nil
}

// 把消息投递到一个实体里
func (p *serverMsgProc) MsgProc_EntityMsgTransport(msg *msgdef.EntityMsgTransport) {
	if msg.SrvType == iserver.ServerTypeClient &&
		p.srv.ServerInfo.Type == iserver.ServerTypeGateway {
		//因为是发给客户端的，可以在这里直接拦截
		ie := p.srv.GetEntity(msg.EntityID)
		if ie == nil {
			return
		}

		te := ie.(iPlayer)
		if clientSess := te.GetClientSess(); clientSess != nil {
			// logger.Debug("EntityMsgTransport to Client.")
			clientSess.SendRaw(msg.MsgContent)
		} else {
			logger.Debug(logger.LogKey_Entity, "EntityMsgTransport to Client failed, UserSess is nil. Is THIS Srv Gateway ??? ")
		}
	} else {
		if es := p.getMsgHandlers(msg.SpaceID); es != nil {
			// logger.Debug("server.EntityMsgTransport:", msg.Name())
			es.FireMsg(msg.Name(), msg)
		}
	}

}

// 把消息投递到一群实体里
func (p *serverMsgProc) MsgProc_EntitysMsgTransport(msg *msgdef.EntitysMsgTransport) {

	if msg.SrvType != iserver.ServerTypeClient {
		//目前设计只用于发消息给客户端
		return
	}
	// logger.Debugf(logger.LogKey_Default, "serverMsgProc.MsgProc_EntitysMsgTransport %p", msg)
	for i := range msg.EntityID {
		ie := p.srv.GetEntity(msg.EntityID[i])
		if ie == nil {
			continue
		}
		te := ie.(iPlayer)
		if clientSess := te.GetClientSess(); clientSess != nil {
			// logger.Debug("EntityMsgTransport to Client.")
			clientSess.SendRaw(msg.MsgContent)
		} else {
			logger.Debug(logger.LogKey_Entity, "serverMsgProc.EntitysMsgTransport to Client failed, UserSess is nil. Is THIS Srv Gateway ??? ")
		}
	}
}

// 把消息投递到一个空间里
func (p *serverMsgProc) MsgProc_SrvMsgTransport(msg *msgdef.SrvMsgTransport) {
	if es := p.getMsgHandlers(msg.SpaceID); es != nil {
		es.FireMsg(msg.Name(), msg)
	} else {
		logger.Error("转发服务器消息时 找不到目标EntityID:", msg)
	}
}

// 把分组消息投递到一个服务器里
func (p *serverMsgProc) MsgProc_SrvGroupMsgTransport(msg *msgdef.SrvGroupMsgTransport) {
	if es := p.getMsgHandlers(0); es != nil {
		es.FireMsg(msg.Name(), msg)
	}
}

// 会话关闭,对应的会话处理,不区分服务器客户端
func (p *serverMsgProc) MsgProc_SessClosed(uid uint64) {
	srv := p.srv
	logger.Info("[serverMsgProc]MsgProc_SessClosed :", uid)
	//服务器断开连接
	srv.OnceTimer(time.Second, srv.srvCtrl.ServerSessClosed, uid)

}

// 客户端验证成功返回
// 我作为客户端,连接到其他服务器了
func (p *serverMsgProc) MsgProc_ClientVerifySucceedRet(msg *msgdef.ClientVerifySucceedRet) {
	p.srv.srvCtrl.ServerSessConnect(msg.SourceID, msg.Type)
	//seelog.Debug("[serverMsgProc]  SrvNet server ", srv.srvID, " connect to sserver ", msg.SourceID, "  succeed")
}
